package com.thn.site.config;

import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * 动态路由配置类
 */
@Configuration
public class NacosDynamicRouteConfig {

    private final RouteDefinitionWriter routeDefinitionWriter;
    private final RouteDefinitionLocator routeDefinitionLocator;

    public NacosDynamicRouteConfig(RouteDefinitionWriter routeDefinitionWriter,
                                   RouteDefinitionLocator routeDefinitionLocator) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    /**
     * 获取当前所有路由定义（供刷新使用）
     */
    public Flux<RouteDefinition> getRoutes() {
        return routeDefinitionLocator.getRouteDefinitions();
    }

    /**
     * 刷新路由定义（清空并重新加载）
     */
    public void refreshRoutes(Flux<RouteDefinition> newRoutes) {
        // 先删除所有现有路由
        getRoutes().flatMap(route -> routeDefinitionWriter.delete(Mono.just(route.getId()))).blockLast();

        // 再添加新路由
        newRoutes.flatMap(route -> routeDefinitionWriter.save(Mono.just(route))).blockLast();
    }
}
